package com.study.chunguard.common.utils.easyexcel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

/**
 * 枚举转换器
 *
 * @author zhaowenhao
 * @since 2023-05-17
 */
@Slf4j
public class EnumConverter implements Converter<Object> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return Object.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Object convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                    GlobalConfiguration globalConfiguration) {
        try {
            Class<?> enumType = getType(contentProperty);
            Object[] enumConstants = enumType.getEnumConstants();
            for (Object enumConstant : enumConstants) {
                Method getName = enumType.getMethod("getName");
                if (getName.invoke(enumConstant).equals(cellData.getStringValue())) {
                    Method getCode = enumType.getMethod("getCode");
                    return getCode.invoke(enumConstant);
                }
            }
        } catch (Exception e) {
            log.error("枚举转换错误", e);
        }
        return null;
    }

    @Override
    public WriteCellData<?> convertToExcelData(Object value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        try {
            Class<?> enumType = getType(contentProperty);
            Object[] enumConstants = enumType.getEnumConstants();
            for (Object enumConstant : enumConstants) {
                Method getCode = enumType.getMethod("getCode");
                if (getCode.invoke(enumConstant).equals(value)) {
                    Method getName = enumType.getMethod("getName");
                    return new WriteCellData<>(String.valueOf(getName.invoke(enumConstant)));
                }
            }
        } catch (Exception e) {
            log.error("枚举转换错误", e);
        }
        return new WriteCellData<>("");
    }

    private static Class<?> getType(ExcelContentProperty contentProperty) {
        return contentProperty.getField().getAnnotation(EnumFormat.class).value();
    }
}
